/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.dxo;

import cc.aileron.accessor.PojoAccessorDxo;
import cc.aileron.commons.utils.CastUtils;

import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * @author Aileron
 */
@Singleton
public class StringToNumberDxo implements
    PojoAccessorDxo.Setter<String, Object>
{
    /**
     * @param p
     * @param r
     * @return object
     */
    public Object convert(final String p,
            final Class<?> r)
    {
        if (Boolean.TYPE == r)
        {
            return Boolean.parseBoolean(p);
        }
        if (Character.TYPE == r)
        {
            throw new UnsupportedOperationException();
        }
        return setter(p, CastUtils.<Class<Object>> cast(r));
    }

    @Override
    public Object setter(final String p,
            final Class<Object> r)
    {
        final Number number = Integer.valueOf(p);
        return dxo.convert(number, r);
    }

    /**
     * @param dxo
     */
    @Inject
    public StringToNumberDxo(final NumberDxo dxo)
    {
        this.dxo = dxo;
    }

    private final NumberDxo dxo;
}
